#coding=utf8
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib import auth
from django.template import RequestContext
from django.contrib.auth.models import *

from django.contrib.auth.decorators import permission_required

from docshare.share.models import *
from docshare.share.tools import *
from docshare.share.forms import *

import settings

def index(request):
    objects = pagerTool(request,subject.objects.all());
    return render_to_response('forum/index.html',{'objects':objects},context_instance=RequestContext(request))


def new(request):
    form = SubForm()
    if request.method == 'POST':
        form = SubForm(request.POST)
        if form.is_valid():
            new_subject=form.save(commit=False)
            new_subject.author = request.user
            new_subject.save()
            return HttpResponseRedirect('/%s/forum/index/'%settings.SITE_ROOT)
    return render_to_response('forum/new.html',{'form':form},context_instance=RequestContext(request))


def show_replies(request,id):
    obj = subject.objects.get(pk=id)
    objects = pagerTool(request,reply.objects.filter(subject=obj))
    obj.read_nums = obj.read_nums + 1
    obj.save()
    form = ReplyForm()
    if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
            new_reply=form.save(commit=False)
            new_reply.subject = obj
            new_reply.author = request.user
            new_reply.save()
            obj = subject.objects.get(pk=id)
            obj.repe_nums = obj.repe_nums + 1
            obj.save()
            return HttpResponseRedirect('/%s/forum/show_replies/%s'%(settings.SITE_ROOT,id))
    return render_to_response('forum/show_replies.html',{'obj':obj,'form':form,'objects':objects},context_instance=RequestContext(request))
